﻿using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace fenban
{
    public class NPOIHelper
    {
        /// <summary>
        /// DataTable导出到Excel文件
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="strHeaderText">表头文本</param>
        /// <param name="strFileName">保存位置</param>
        public static void ExportByServer(DataTable dtSource, string strHeaderText, string strFileName)
        {
            using (MemoryStream ms = Export(dtSource, strHeaderText))
            {
                using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
                {
                    byte[] data = ms.ToArray();
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                }
            }
        }

        /// <summary>
        /// Excel导入成Datable
        /// </summary>
        /// <param name="file">导入路径(包含文件名与扩展名)</param>
        /// <returns></returns>
        public static DataTable ExcelToTable(string file)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
                if (workbook == null) { return null; }
                ISheet sheet = workbook.GetSheetAt(0);

                //表头  
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueType(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据  
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }
        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }

        /// <summary>读取excel
        /// 默认第一行为标头
        /// </summary>
        /// <param name="strFileName">excel文档路径</param>
        /// <returns></returns>
        public static DataTable Import(string strFileName)
        {
            DataTable dt = new DataTable();

            HSSFWorkbook hssfworkbook;
            using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
            {
                hssfworkbook = new HSSFWorkbook(file);
            }
            ISheet sheet = hssfworkbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

            IRow headerRow = sheet.GetRow(0);
            int cellCount = headerRow.LastCellNum;

            for (int j = 0; j < cellCount; j++)
            {
                ICell cell = headerRow.GetCell(j);
                dt.Columns.Add(cell.ToString());
            }

            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                DataRow dataRow = dt.NewRow();

                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                        dataRow[j] = row.GetCell(j).ToString();
                }

                dt.Rows.Add(dataRow);
            }
            return dt;
        }


        /// <summary>
        /// DataTable导出到Excel的MemoryStream
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="strHeaderText">表头文本</param>
        public static MemoryStream Export(DataTable dtSource, string strHeaderText)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet();

            #region 右击文件 属性信息
            {
                DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                dsi.Company = "Sohu";
                workbook.DocumentSummaryInformation = dsi;

                SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                si.Author = "文件作者信息"; //填加xls文件作者信息
                si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息
                si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息
                si.Comments = "作者信息"; //填加xls文件作者信息
                si.Title = "标题信息"; //填加xls文件标题信息
                si.Subject = "主题信息";//填加文件主题信息
                si.CreateDateTime = DateTime.Now;
                workbook.SummaryInformation = si;
            }
            #endregion

            ICellStyle dateStyle = workbook.CreateCellStyle();
            IDataFormat format = workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

            //取得列宽
            int[] arrColWidth = new int[dtSource.Columns.Count];
            foreach (DataColumn item in dtSource.Columns)
            {
                arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
            }
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                    if (intTemp > arrColWidth[j])
                    {
                        arrColWidth[j] = intTemp;
                    }
                }
            }
            int rowIndex = 0;
            foreach (DataRow row in dtSource.Rows)
            {
                #region 新建表，填充表头，填充列头，样式
                if (rowIndex == 65535 || rowIndex == 0)
                {
                    if (rowIndex != 0)
                    {
                        sheet = workbook.CreateSheet();
                    }

                    #region 表头及样式
                    {
                        IRow headerRow = sheet.CreateRow(0);
                        headerRow.HeightInPoints = 25;
                        headerRow.CreateCell(0).SetCellValue(strHeaderText);

                        ICellStyle headStyle = workbook.CreateCellStyle();
                        headStyle.Alignment = HorizontalAlignment.Center;
                        IFont font = workbook.CreateFont();
                        font.FontHeightInPoints = 20;
                        font.Boldweight = 700;
                        headStyle.SetFont(font);
                        headerRow.GetCell(0).CellStyle = headStyle;
                        sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));

                    }
                    #endregion


                    #region 列头及样式
                    {
                        IRow headerRow = sheet.CreateRow(1);

                        ICellStyle headStyle = workbook.CreateCellStyle();
                        headStyle.Alignment = HorizontalAlignment.Center;


                        IFont font = workbook.CreateFont();
                        font.FontHeightInPoints = 10;
                        font.Boldweight = 700;
                        headStyle.SetFont(font);
                        foreach (DataColumn column in dtSource.Columns)
                        {
                            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                            headerRow.GetCell(column.Ordinal).CellStyle = headStyle;

                            //设置列宽
                            sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
                        }

                    }
                    #endregion

                    rowIndex = 2;
                }
                #endregion


                #region 填充内容
                IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
                    ICell newCell = dataRow.CreateCell(column.Ordinal);

                    string drValue = row[column].ToString();

                    switch (column.DataType.ToString())
                    {
                        case "System.String"://字符串类型
                            newCell.SetCellValue(drValue);
                            break;
                        case "System.DateTime"://日期类型
                            DateTime dateV;
                            DateTime.TryParse(drValue, out dateV);
                            newCell.SetCellValue(dateV);

                            newCell.CellStyle = dateStyle;//格式化显示
                            break;
                        case "System.Boolean"://布尔型
                            bool boolV = false;
                            bool.TryParse(drValue, out boolV);
                            newCell.SetCellValue(boolV);
                            break;
                        case "System.Int16"://整型
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV = 0;
                            int.TryParse(drValue, out intV);
                            newCell.SetCellValue(intV);
                            break;
                        case "System.Decimal"://浮点型
                        case "System.Double":
                            double doubV = 0;
                            double.TryParse(drValue, out doubV);
                            newCell.SetCellValue(doubV);
                            break;
                        case "System.DBNull"://空值处理
                            newCell.SetCellValue("");
                            break;
                        default:
                            newCell.SetCellValue("");
                            break;
                    }

                }
                #endregion

                rowIndex++;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;

                //sheet.Dispose();
                //workbook.Dispose();//一般只用写这一个就OK了，他会遍历并释放所有资源，但当前版本有问题所以只释放sheet
                return ms;
            }
        }


        /// <summary>
        /// DataTable按模板导出到Excel文件
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="TempletFileName">模板文件</param>
        /// <param name="strFileName">保存位置</param>
        public static void ExportByTemplate(string TempletFileName, string strFileName, DataTable dt, string Type)
        {
            using (MemoryStream ms = ExportByTemp(TempletFileName, dt, Type))
            {
                using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
                {
                    byte[] data = ms.ToArray();
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                }
            }
        }
        /// <summary>
        /// DataTable导出到Excel的MemoryStream
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="TempletFileName">Excel模板</param>
        /// <returns></returns>
        public static MemoryStream ExportByTemp(string TempletFileName, DataTable dt, string Type)
        {
            FileStream file = new FileStream(TempletFileName, FileMode.Open, FileAccess.Read);

            HSSFWorkbook workbook = new HSSFWorkbook(file);
            ISheet sheet = workbook.GetSheetAt(1);

            //ICellStyle dateStyle = workbook.CreateCellStyle();
            //dateStyle.BorderBottom = BorderStyle.Thin;
            //dateStyle.BorderLeft = BorderStyle.Thin;
            //dateStyle.BorderRight = BorderStyle.Thin;
            //dateStyle.BorderTop = BorderStyle.Thin;

            int rowIndex = 0;

            foreach (DataRow entity in dt.Rows)
            {
                IRow dataRow = sheet.CreateRow(rowIndex);

                if (Type.Equals("SaleType"))
                {
                    ICell newCell0 = dataRow.CreateCell(0);
                    newCell0.SetCellValue(entity[2].ToString());
                    //newCell0.CellStyle = dateStyle;
                }
                else
                {
                    ICell newCell0 = dataRow.CreateCell(0);
                    newCell0.SetCellValue(entity[1].ToString());
                    //newCell0.CellStyle = dateStyle;
                }
                //ICell newCell7 = dataRow.CreateCell(7);
                //if (type.Equals("excel"))
                //{
                //    newCell7.SetCellValue(entity.Location == "" ? "" : "第" + entity.Location + "行");
                //}
                //else if (type.Equals("word"))
                //{
                //    newCell7.SetCellValue(entity.Location == "" ? "" : "第" + entity.Location + "页");
                //}
                //newCell7.CellStyle = dateStyle;



                rowIndex++;
            }
            if (dt.Rows.Count == 1)
            {
                IRow dataRow = sheet.CreateRow(rowIndex);
                ICell newCelllast = dataRow.CreateCell(0);
                newCelllast.SetCellValue(" ");
            }



            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;

                //sheet.Dispose();
                //workbook.Dispose();//一般只用写这一个就OK了，他会遍历并释放所有资源，但当前版本有问题所以只释放sheet
                return ms;
            }
        }


        public static void ExportByNodeData(string TfileName, string StrfileName, DataTable dt, string Type, double Rate)
        {
            using (MemoryStream ms = ExportByNode(TfileName, dt, Type, Rate))
            {
                using (FileStream fs = new FileStream(StrfileName, FileMode.Create, FileAccess.Write))
                {
                    byte[] data = ms.ToArray();
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                }
            }
        }
        public static MemoryStream ExportByNode(string TempletFileName, DataTable dt, string Type, double Rate)
        {
            FileStream file = new FileStream(TempletFileName, FileMode.Open, FileAccess.Read);

            HSSFWorkbook workbook = new HSSFWorkbook(file);
            ISheet sheet = workbook.GetSheetAt(0);

            ICellStyle dateStyle = workbook.CreateCellStyle();
            dateStyle.BorderBottom = BorderStyle.Thin;
            dateStyle.BorderLeft = BorderStyle.Thin;
            dateStyle.BorderRight = BorderStyle.Thin;
            dateStyle.BorderTop = BorderStyle.Thin;

            int rowIndex = 1;

            foreach (DataRow entity in dt.Rows)
            {
                IRow dataRow = sheet.CreateRow(rowIndex);

                if (Type.Equals("SaleTypeExport"))
                {
                    ICell newCell0 = dataRow.CreateCell(0);
                    newCell0.SetCellValue(rowIndex);
                    newCell0.CellStyle = dateStyle;

                    ICell newCell1 = dataRow.CreateCell(1);
                    newCell1.SetCellValue(entity["new_nodename"].ToString());
                    newCell1.CellStyle = dateStyle;

                    ICell newCell2 = dataRow.CreateCell(2);
                    newCell2.SetCellValue(Convert.ToDouble(entity["new_lastyear_total"].ToString()));
                    newCell2.CellStyle = dateStyle;

                    ICell newCell3 = dataRow.CreateCell(3);
                    newCell3.SetCellValue(Convert.ToDouble(entity["new_total_assign2me"].ToString()));
                    newCell3.CellStyle = dateStyle;

                    ICell newCell4 = dataRow.CreateCell(4);
                    newCell4.SetCellValue(Convert.ToInt32(entity["new_accountadd"].ToString()));
                    newCell4.CellStyle = dateStyle;

                    ICell newCell5 = dataRow.CreateCell(5);
                    newCell5.SetCellValue(Convert.ToDouble(entity["new_total_assign2me"].ToString()) - (Convert.ToDouble(entity["new_total_assign2me"].ToString()) * Rate));
                    newCell5.CellStyle = dateStyle;

                    ICell newCell6 = dataRow.CreateCell(6);
                    newCell6.SetCellValue((Convert.ToDouble(entity["new_total_assign2me"].ToString()) * Rate));
                    newCell6.CellStyle = dateStyle;

                    ICell newCell7 = dataRow.CreateCell(7);
                    newCell7.SetCellValue(Convert.ToDouble(entity["RefeAmount"].ToString()));
                    newCell7.CellStyle = dateStyle;

                    ICell newCell8 = dataRow.CreateCell(8);
                    newCell8.SetCellValue(entity["new_description"].ToString());
                    newCell8.CellStyle = dateStyle;
                }
                else if (Type.Equals("AccountTypeExport"))
                {
                    ICell newCell0 = dataRow.CreateCell(0);
                    newCell0.SetCellValue(rowIndex);
                    newCell0.CellStyle = dateStyle;

                    ICell newCell1 = dataRow.CreateCell(1);
                    newCell1.SetCellValue(entity["new_name"].ToString());
                    newCell1.CellStyle = dateStyle;

                    ICell newCell2 = dataRow.CreateCell(2);
                    newCell2.SetCellValue(Convert.ToDouble(entity["new_lastyear_total"].ToString()));
                    newCell2.CellStyle = dateStyle;

                    ICell newCell3 = dataRow.CreateCell(3);
                    newCell3.SetCellValue(Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()));
                    newCell3.CellStyle = dateStyle;

                    ICell newCell4 = dataRow.CreateCell(4);
                    newCell4.SetCellValue(Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) - (Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) * Rate));
                    newCell4.CellStyle = dateStyle;

                    ICell newCell5 = dataRow.CreateCell(5);
                    newCell5.SetCellValue((Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) * Rate));
                    newCell5.CellStyle = dateStyle;

                    ICell newCell6 = dataRow.CreateCell(6);
                    newCell6.SetCellValue(Convert.ToDouble(entity["RefeAmount"].ToString()));
                    newCell6.CellStyle = dateStyle;

                    ICell newCell7 = dataRow.CreateCell(7);
                    newCell7.SetCellValue(entity["new_nodetemdesc_description"].ToString());
                    newCell7.CellStyle = dateStyle;
                }
                else if (Type.Equals("NodeDescByAccountExport"))
                {
                    ICell newCell0 = dataRow.CreateCell(0);
                    newCell0.SetCellValue(rowIndex);
                    newCell0.CellStyle = dateStyle;

                    ICell newCell1 = dataRow.CreateCell(1);
                    newCell1.SetCellValue(entity["new_name"].ToString());
                    newCell1.CellStyle = dateStyle;

                    ICell newCell2 = dataRow.CreateCell(2);
                    newCell2.SetCellValue(Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()));
                    newCell2.CellStyle = dateStyle;

                    ICell newCell3 = dataRow.CreateCell(3);
                    newCell3.SetCellValue(Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) - (Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) * Rate));
                    newCell3.CellStyle = dateStyle;

                    ICell newCell4 = dataRow.CreateCell(4);
                    newCell4.SetCellValue((Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) * Rate));
                    newCell4.CellStyle = dateStyle;

                    ICell newCell5 = dataRow.CreateCell(5);
                    newCell5.SetCellValue(Convert.ToDouble(entity["RefeAmount"].ToString()));
                    newCell5.CellStyle = dateStyle;

                    ICell newCell6 = dataRow.CreateCell(6);
                    newCell6.SetCellValue(entity["new_nodetemdesc_description"].ToString());
                    newCell6.CellStyle = dateStyle;
                }
                else if (Type.Equals("NodeDescBySaleExport"))
                {
                    ICell newCell0 = dataRow.CreateCell(0);
                    newCell0.SetCellValue(rowIndex);
                    newCell0.CellStyle = dateStyle;

                    ICell newCell1 = dataRow.CreateCell(1);
                    newCell1.SetCellValue(entity["new_name"].ToString());
                    newCell1.CellStyle = dateStyle;

                    ICell newCell2 = dataRow.CreateCell(2);
                    newCell2.SetCellValue(Convert.ToDouble(entity["new_distributeamount"].ToString()));
                    newCell2.CellStyle = dateStyle;

                    ICell newCell3 = dataRow.CreateCell(3);
                    newCell3.SetCellValue(Convert.ToDouble(entity["new_distributeamount"].ToString()) - (Convert.ToDouble(entity["new_distributeamount"].ToString()) * Rate));
                    newCell3.CellStyle = dateStyle;

                    ICell newCell4 = dataRow.CreateCell(4);
                    newCell4.SetCellValue((Convert.ToDouble(entity["new_distributeamount"].ToString()) * Rate));
                    newCell4.CellStyle = dateStyle;

                    ICell newCell5 = dataRow.CreateCell(5);
                    newCell5.SetCellValue(Convert.ToDouble(entity["RefeAmount"].ToString()));
                    newCell5.CellStyle = dateStyle;

                    ICell newCell6 = dataRow.CreateCell(6);
                    newCell6.SetCellValue(entity["new_description"].ToString());
                    newCell6.CellStyle = dateStyle;
                }
                rowIndex++;
            }

            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;

                //sheet.Dispose();
                //workbook.Dispose();//一般只用写这一个就OK了，他会遍历并释放所有资源，但当前版本有问题所以只释放sheet
                return ms;
            }
        }

    }
}
